//
//  HomeOwnViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
import SwiftUI
class ChatRecordViewModel : BaseViewModel {
    @Published var items = [ChatRecordBean]()
    @Published var status = ""
    
    func getHideChatRecordList() -> [String] {
        let dict = try? fromJson(AppStorageManager.shared.hideChatRecord,  [String].self)
        return dict ?? []
    }
    
    override init() {
        super.init()
        self.pageSize = 1000
        self.addObserve(self, .updateAiRole) { (selfInstance, update: Bool) in
            //刷新ai列表
            selfInstance.items.removeAll()
            selfInstance.getData()
        }
        self.addObserve(self, .addChat) { (selfInstance, bean: ChatBean) in
            //执行显示操作，并且刷新
            selfInstance.doShowChatRecord(roleId: bean.role?.roleId) {
                selfInstance.getData()
            }
        }
    }
    
    
    
    func getData() {
        showLog("查询角色")
        requestList {
            let aiRoleOften = try await BackupsManager.shared.getDelegateConfig()?.getOften()

            let hideChatRecordList : [String] = self.getHideChatRecordList()//隐藏的id
            var listAll : [ChatRecordBean] = []
            var list = try await BackupsManager.shared.getDelegateConfig()?.getAiRoleList(false) ?? []
            list = list.filter { !($0.hideChatRecord ?? false) && !hideChatRecordList.contains($0.objectId ?? "")}
            listAll.append(contentsOf: list.compactMap {
               var record = ChatRecordBean(role: $0)
                record.aiRoleOften = aiRoleOften
            return record
            })
            for index in listAll.indices {
                //查询最后一条记录
                listAll[index].chat = try await self.getLastRecord(roleBean: listAll[index].role)
            }
            listAll.sort { $0.chat?.time ?? 0 > $1.chat?.time ?? 0 }
            return listAll
        } suc: {
            self.items = $0
            showLog($0)
        } fail: {
            let toast = $0.message
            showLog("获取角色列表报错：\(toast)")
            showToast(toast)
        }
    }
    
    func getLastRecord(roleBean: AiRoleBean) async throws -> ChatBean? {
        let lastChatBean = try await BackupsManager.shared.getDelegateDiary()?.queryNewChat(aiUserId: roleBean.objectId ?? "", userId: BackupsManager.shared.backupsType == BackupsType.cloud ? userManager.getUserId() : "")
        return lastChatBean
    }
    
    func doHideChatRecord(bean: AiRoleBean) {
        request(isLoading: false) {
            var hideChatRecordList : [String] = self.getHideChatRecordList()//隐藏的id
            if (bean.isSystem ?? false) {
                //由于系统的无法保存，则存储在本地
                if !hideChatRecordList.contains(bean.objectId ?? "") {
                    hideChatRecordList.append(bean.objectId ?? "")
                }
            } else {
                bean.hideChatRecord = true
                let _ = try await BackupsManager.shared.getDelegateConfig()?.addAiRole(bean: bean, isAdd: false)
            }
            return hideChatRecordList
        } suc: { hideChatRecordList in
            AppStorageManager.shared.hideChatRecord = toJson(array: hideChatRecordList)
            self.getData()
        } fail: {
            showToast($0.message)
        }
    }
    
    func doShowChatRecord(roleId: String?,suc: @escaping ()->Void) {
        if ((roleId ?? "")?.isEmpty == true) {
            suc()
            return
        }
        request(isLoading: false) {
            var hideChatRecordList : [String] = self.getHideChatRecordList()//隐藏的id
            let bean = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: roleId)
            try check(bean != nil, "找不到该角色")
            if (bean?.isSystem ?? false) {
                //由于系统的无法保存，则存储在本地
                if !hideChatRecordList.contains(bean?.objectId ?? "") {
                    if let objectId = bean?.objectId {
                        hideChatRecordList.removeAll { $0 == objectId }
                    }
                }
            } else {
                bean?.hideChatRecord = false
                let _ = try await BackupsManager.shared.getDelegateConfig()?.addAiRole(bean: bean!, isAdd: false)
            }
            return hideChatRecordList
        } suc: { hideChatRecordList in
            AppStorageManager.shared.hideChatRecord = toJson(array: hideChatRecordList)
            suc()
        } fail: {
            showToast($0.message)
        }
    }
    
    func reset() {
        isInit = false
        items.removeAll()
    }
}
